﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http.Dependencies;
using System.Web.Http;
using OA.DAL;
using Autofac.Integration.WebApi;
using OA.WebAPI.Filtes;

namespace OA.WebAPI.App_Start
{
	public class AutofacConfig
	{
		public static void Register()
		{
            var builder = new ContainerBuilder();
            //加载当前程序集
            Assembly controllerAss = Assembly.GetExecutingAssembly();
            //注册所有的Controller
            builder.RegisterApiControllers(controllerAss)  //注册WebAPI控制器
                     .PropertiesAutowired(); // 属性注入方式

            // 注册全局过滤器
            builder.RegisterType(typeof(OAAuthAttribute))
                .PropertiesAutowired() // 属性注入
                .SingleInstance();   // 生命周期：单例
            builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);  // 注册过滤器

            //注册数据层程序集
            Assembly dalAss = Assembly.Load("OA.DAL");
            builder.RegisterAssemblyTypes(dalAss)
            //builder.RegisterTypes(dalAss.GetTypes())
                .PropertiesAutowired()
                .InstancePerLifetimeScope()
                .AsImplementedInterfaces();
            //注册业务层程序集
            Assembly bllAss = Assembly.Load("OA.BLL");
            builder.RegisterAssemblyTypes(bllAss)
                // builder.RegisterTypes(bllAss.GetTypes())
                .PropertiesAutowired()
                .AsImplementedInterfaces();
            // 单独注册“数据库上下文”，会覆盖前面的注册
            builder.RegisterType<OADbContext>().InstancePerLifetimeScope();

            var container = builder.Build();
            GlobalConfiguration.Configuration.DependencyResolver 
                = new AutofacWebApiDependencyResolver(container);

        }
	}
}